﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Miao
{
    /// <summary>
    /// 所有要具备回收的类由PoolManager生成
    /// </summary>
    public static class GameObjectPoolManager
    {
        static Dictionary<string, GameObjectPool> AllPool = new Dictionary<string, GameObjectPool>();
        /// <summary>
        /// 创建基于Preafab的GameObject
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="components"></param>
        /// <returns></returns>
        public static GameObject CreateGameObject(Transform parent, GameObject prefab)
        {
            string Key = prefab.name;
            if (AllPool.ContainsKey(Key))
            {
                return AllPool[Key].Spawn(parent);
            }
            else
            {
                GameObjectPool TypePool = new GameObjectPool(prefab);
                AllPool.Add(Key, TypePool);
                return TypePool.Spawn(parent);
            }
        }
        public static void RemoveGameObject(GameObject Instance)
        {
            string Key = Instance.name;
            AllPool[Key].Despawn(Instance);
        }
        /// <summary>
        /// 适用于场景切换清空池缓存，注意场景物件并不会回收。
        /// </summary>
        /// <param name="Instance"></param>
        public static void RemovePool(GameObject Instance)
        {
            string Key = Instance.name;
            AllPool.Remove(Key);
        }

        /// <summary>
        /// 创建动态GameObject
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="components"></param>
        /// <returns></returns>
        public static GameObject CreateGameObjectType(Transform parent, params Type[] components)
        {
            string Key = default;
            foreach (Type type in components)
            {
                Key += type.Name;
            }
            if (AllPool.ContainsKey(Key))
            {
                return AllPool[Key].Spawn(parent);
            }
            else
            {
                GameObjectPool TypePool = new GameObjectPool(components);
                AllPool.Add(Key, TypePool);
                return TypePool.Spawn(parent);
            }
        }
        /// <summary>
        /// 回收基于池的GameObject
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="components"></param>
        /// <returns></returns>
        public static void RemoveGameObjectType(GameObject Instance, params Type[] components)
        {
            string Key = "";
            foreach (Type type in components)
            {
                Key += type.Name;
            }
            AllPool[Key].Despawn(Instance);
        }



    }
}
